package com.whz.streamdemo;

import lombok.extern.slf4j.Slf4j;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;

/**
 * @Author: sinosoft
 * @Description: 实现输入列表的所以子列表
 * (a,b,c)的前缀(a),(a,b),(a,b,c)
 * (a,b,c)的后缀(a,b,c),(b,c),(c)
 * 集合的所有子列表是前缀的后缀和空列表
 * @Date: Create in 19:47 2021/5/18
 * @Modified By:
 */
@Slf4j
public class SubLists {

    public static <E> Stream<List<E>> of(List<E> list) {
        return Stream.concat(Stream.of(Collections.emptyList()),
                prefixes(list).flatMap(SubLists::suffixes));
    }
    // 前缀
    private static <E> Stream<List<E>> prefixes(List<E> list) {
        log.info("{} 的前缀", list);
        return IntStream.rangeClosed(1, list.size())
                .mapToObj(end -> list.subList(0, end));
    }
    // 后缀
    private static <E> Stream<List<E>> suffixes(List<E> list) {
        log.info("{} 的后缀", list);
        return IntStream.range(0, list.size())
                .mapToObj(start -> list.subList(start, list.size()));
    }
}
